package com.simtop.beefsheepmaching.config;

import com.alibaba.fastjson.JSONObject;
import com.simtop.beefsheepmaching.common.ServerResponse;
import com.simtop.beefsheepmaching.pojo.User;
import com.simtop.beefsheepmaching.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lvyongwei
 * @description 拦截请求
 */
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ((request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        //获取前端传来的token
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("Authorization");
        if(token == null){
            response.getWriter().write(JSONObject.toJSONString(ServerResponse.createByErrorMsg("请登录后操作")));
            return false;
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            response.getWriter().print(JSONObject.toJSONString(ServerResponse.createByErrorMsg("token无效")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
